//
//  SeekCarViewController.m
//  cityCar
//
//  Created by yao on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SeekCarViewController.h"
#import "UIImageView+WebCache.h"
#import "SeekBrandCell.h"
#import "SeekExactCell.h"
//#import "SeekExactBaseView.h"
#import "SeekSelectViewController.h"
#import "SeekWebViewController.h"
#import "ForumGather.h"
#import "Car.h"

@interface SeekCarViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain)UICollectionView *collection;
@property(nonatomic, retain)UISegmentedControl *segment;

// 存入本地
@property(nonatomic, retain)NSMutableArray *recentlyArray;

@end

@implementation SeekCarViewController

- (void)dealloc
{
    [_collection release];
    [_segment release];
    [_recentlyArray release];
    // 移除通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //        self.dictionary = [NSMutableDictionary dictionary];
        
        self.recentlyArray = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self     setupViews];
    
}
- (void)setupViews
{
    self.title = @"找车";
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"品牌选车", @"精准选车"]];
    self.segment.frame = CGRectMake(30, 64, self.view.frame.size.width - 60, 27);
    // segment加一个方法
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:(UIControlEventValueChanged)];
    // segment默认选择下标0
    self.segment.selectedSegmentIndex = 0;
    self.segment.tintColor = [WebColor darkGray];
    [self.view addSubview:self.segment];
    
    // collectionView布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 140);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 1;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 91, self.view.frame.size.width, self.view.frame.size.height - 140) collectionViewLayout:flowLayout];
    self.collection.delegate   = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [UIColor whiteColor];
    self.collection.showsHorizontalScrollIndicator = NO;
    self.collection.pagingEnabled = YES;
    // 注册自定义cell
    [self.collection registerClass:[SeekBrandCell class] forCellWithReuseIdentifier:@"reuse1"];
    // 注册自定义cell
    [self.collection registerClass:[SeekExactCell class] forCellWithReuseIdentifier:@"reuse2"];
    // 注册系统cell
    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.view addSubview:self.collection];
    
    //  内存释放
    [_segment release];
    [flowLayout release];
    [_collection release];
}
- (void)segmentAction:(UISegmentedControl *)segment
{
    switch (segment.selectedSegmentIndex) {
        case 0:
            // 选择segment下标，对应collection位置
            self.collection.contentOffset = CGPointMake(0, 0);
            break;
        case 1:
            self.collection.contentOffset = CGPointMake(self.view.frame.size.width, 0);
            break;
        default:
            break;
    }
}
// 滑动页面时 使segment和当前页面对应上
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int number = scrollView.contentOffset.x / scrollView.frame.size.width;
    self.segment.selectedSegmentIndex = number;
}
// collectionView的cell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            // 第0个cell
            SeekBrandCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse1" forIndexPath:indexPath];
            
            void(^block)(Car *, NSString *) = ^(Car *car, NSString *IdUrl){
                // 收到通知后执行的方法，跳转到webView页面
                SeekWebViewController *seekWeb = [[SeekWebViewController alloc] init];
                // 通知中心传来的Id赋给seekWeb
                seekWeb.car = car;
                seekWeb.Idurl = IdUrl;
                
                // 创建forumGather对象，存到recentlyArray数组中，并存入本地，显示在最近访问中。
                ForumGather *forum = [[ForumGather alloc] init];
                forum.url = IdUrl;
                forum.Id = car.Id;
                forum.name = car.name;
                
                // 存本地之前先从本地读取
                static int temp = 1;
                if (temp == 1) {
                    NSArray *achieveArray = [self achieveDate];
                    if (achieveArray.count != 0) {
                        [self.recentlyArray addObjectsFromArray:achieveArray];
                    }
                    temp = 0;
                }
                
                int flag = 1;
                for (ForumGather *fo in self.recentlyArray) {
                    NSString *Id = [NSString stringWithFormat:@"%@", forum.Id];
                    NSString *foId = [NSString stringWithFormat:@"%@", fo.Id];
                    if ([Id isEqualToString:foId]) {
                        
                        flag = 0;
                    }
                }
                if (flag == 1) {
                    [self.recentlyArray addObject:forum];
                }
                
                // 写入本地
                [self locationStore];
                [self.navigationController pushViewController:seekWeb animated:YES];
                [seekWeb release];
                [forum release];

            };
            
            cell1.brandView.block = block;
            return cell1;
        }
            break;
        case 1:
        {
            // 第1个cell
            SeekExactCell *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse2" forIndexPath:indexPath];
            // block传值的第一步
            // 将seekExactView中的4个value字典传来
            void(^blockValue)(NSMutableDictionary *Seekdic) = ^(NSMutableDictionary *Seekdic) {
                SeekSelectViewController *select = [[SeekSelectViewController alloc] init];
                // 再把从view传来的字典赋给
                select.dictionary = Seekdic;
                // 推到精准选车选出来的车的页面
              
                [self.navigationController pushViewController:select animated:YES];
                
            };
            // 把block的钥匙传给exactView
            cell2.exactView.blockValue = blockValue;
            return cell2;
        }
            break;
        default:
        {
            UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
            return cell;
        }
            break;
    }
    
}

// 存本地之前先从本地读取
- (NSArray *)achieveDate
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths lastObject];
    NSArray *achieveArray = [NSArray array];
    NSString *carPath = [documentPath stringByAppendingPathComponent:@"recentlyCar.aaa"];
    achieveArray = [NSKeyedUnarchiver unarchiveObjectWithFile:carPath];
    
    return achieveArray;
    
}


// 本地存储
- (void)locationStore
{
    // 找到沙盒的路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    // 获取documents的路径
    NSString *documentPath = [paths objectAtIndex:0];
    
    // 归档类，将一个实现了NSCoding协议的对象，写入本地
    NSString *carPath = [documentPath stringByAppendingPathComponent:@"recentlyCar.aaa"];
    
    if (self.recentlyArray.count > 4) {
        for (int i = 0; i < self.recentlyArray.count - 4 + i; i++) {
            [self.recentlyArray removeObjectAtIndex:0];
        }
    }
    
    BOOL carResult = [NSKeyedArchiver archiveRootObject:self.recentlyArray toFile:carPath];
    NSLog(@"最近访问写入本地：%d", carResult);
    
    
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
